<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/21
 * Time: 14:23
 */

class Purchaser extends ADM_Controller
{
    /**
     * Purchaser constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 取消
     */
    public function cancel()
    {
        $send['state'] = false;
        do {

            $id = $this->input->get('id');
            if (empty($id)) {
                $send['error'] = '参数错误';
                break;
            }

            $db = clone($this->db);
            $q = $db->get_where('base_bill_apply', ['id' => $id]);
            $item = $q->row_array();
            if (empty($item)) {
                $send['error'] = '对账单不存在';
                break;
            }

            if ($this->baseId != $item['baseId']) {
                $send['error'] = '权限不足';
                break;
            }

            if ($item['status'] == 6) {
                $send['error'] = '该订单已审核完成';
                break;
            }

            $db2 = clone ($this->db);
            $db2->where('id', $id);
            $db2->delete('base_bill_apply');
            if ($db2->affected_rows()) {
                $send['state'] = true;
            } else {
                $send['error'] = '取消失败';
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     *
     */
    public function apply()
    {
        $send['state'] = false;
        do {

            $params = $this->input->post();
            if (empty($params) || empty($params['year']) || empty($params['month'])) {
                $send['error'] = '参数错误';
                break;
            }

            $bank = $this->getBank();
            $data = $this->getData($params);
            if (empty($bank) || empty($data)) {
                $send['error'] = '未知错误';
                break;
            }

            $d = [
                'baseId' => $this->baseId,
                'adminId' => adminId(),
                'total' => $data['total'] * 100,
                'refund' => $data['refund'] * 100,
                'count' => $data['count'],
                'left' => ($data['total'] - $data['refund'] - $data['delivery']) * 100,
                'delivery' => $data['delivery'] * 100,
                'fx' => 0 * 100,
                'orderStartId' => 0,
                'orderEndId' => 0,
                'year' => $params['year'],
                'month' => $params['month'],
                'status' => 0,
                'bankname' => $bank['bankname'],
                'kaihuhang' => $bank['kaihuhang'],
                'username' => $bank['username'],
                'created' => date('Y-m-d H:i:s'),
                'account' => $bank['account']
            ];

            $this->db->insert('base_bill_apply', $d);
            if ($this->db->insert_id()) {
                $send['state'] = true;
            } else {
                $send['error'] = '对账申请失败';
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     * 主程序
     */
    public function index()
    {
        $this->load->view('admin/money/purchaser/apply.html', [
            'baseId' => $this->baseId
        ]);
    }

    /**
     *
     */
    public function check()
    {
        $p = $this->input->get();
        if (empty($p) || empty($p['year']) || empty($p['month'])) {
            echo 'page error';
            return false;
        }

        $data = $this->getData($p);
        $this->load->view('admin/money/purchaser/check.html', [
            'info' => $data,
            'bank' => $this->getBank()
        ]);
    }

    /**
     * 查看订单
     */
    public function checkOrder()
    {
        $send['state'] = false;
        do {

            $params = $this->input->get();

            if (empty($params) || empty($params['year']) || empty($params['month'])) {
                $send['error'] = '请选择查询时间段';
                break;
            }

            // 有没有生成过账单
            $q = $this->db->get_where('base_bill_apply', [
                'year' => $params['year'],
                'month' => $params['month']
            ]);

            if (!empty($q->row_array())) {
                $send['error'] = '该月份账单已经申请，请查看历史对账单';
                break;
            }

            $send['state'] = true;
            $send['baseId'] = $this->baseId;
            $send['data'] = $this->getData($params);
        } while(false);
        $this->output->send($send);
    }

    /**
     * @return mixed
     */
    public function getBank()
    {
        $q = $this->db->get_where('base_bank', ['baseId' => $this->baseId]);
        return $q->row_array();
    }

    /**
     * @param $params
     */
    public function getData($params)
    {
        $data = [
            'count' => 0,
            'total' => money_format('%i', 0),
            'refund' => money_format('%i', 0),
            'amount' => money_format('%i', 0),
            'delivery' => money_format('%i', 0),
            'lists' => []
        ];

        $this->load->model('common/Order_Model', 'o');
        $res = $this->o->checkOrder($params['year'], $params['month'], $this->baseId);

        $totalPrice = 0;
        $refundPrice = 0;
        $delivery = 0;
        if (!empty($res)) foreach ($res as &$item) {
            $totalPrice += intval($item['totalPrice']);
            if ($item['status'] == 'Refunded') {
                $refundPrice += intval($item['goodsPrice']);
            }
            if ($item['payMode'] == 'delivery') {
                $delivery += intval($item['totalPrice']);
            }
            $item['totalPrice'] = money_format('%i', $item['totalPrice'] / 100);
            $item['goodsPrice'] = money_format('%i', $item['goodsPrice'] / 100);
            $item['expressPrice'] = money_format('%i', $item['expressPrice'] / 100);
        }

        $data['lists'] = $res;
        $data['count'] = !empty($res) ? count($res) : 0;
        $data['total'] = money_format('%i', $totalPrice / 100);
        $data['refund'] = money_format('%i', $refundPrice / 100);
        $data['amount'] = money_format('%i', ($totalPrice - $refundPrice - $delivery) / 100);

        return $data;
    }
}